package com.test45_JUC;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * CompletableFuture，异步处理计算
 */
public class Demo15_CompletableFuture {

    public static void main(String[] args) throws Exception {
        // test1();
        test2();
    }

    /**
     * 同步线程操作
     */
    public static void test1() throws Exception {
        CompletableFuture<String> future = new CompletableFuture<>();
        for (int x = 0; x < 2; x++) {
            new Thread(() -> {
                System.out.printf("【START】%s，炮兵就位，等待开炮命令发出。%n", Thread.currentThread().getName());
                try {
                    System.err.printf("【END】%s，解除阻塞，收到执行命令：%s%n", Thread.currentThread().getName(), future.get());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, "炮兵-" + x).start();
            TimeUnit.SECONDS.sleep(1);
        }
        future.complete("开炮");
    }

    /**
     * 使用异步命令
     */
    public static void test2() throws Exception {
        // 异步线程不用考虑返回值
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            System.err.println("【*** 异步线程 ***】突然接到了上将军的紧急联系电话。");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.err.println("【*** 异步线程 ***】突然接到了新的作战任务，更改炮兵的作战目标。");
        });
        for (int x = 0; x < 2; x++) {
            new Thread(() -> {
                System.out.printf("【START】%s，炮兵就位，等待开炮命令发出。%n", Thread.currentThread().getName());
                try {
                    future.get();
                    System.err.printf("【END】%s，收到开火命令，万炮齐名。%n", Thread.currentThread().getName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, "炮兵-" + x).start();
        }
        System.out.println("【★主线程★】所有的炮兵线程进入到了就绪状态，等待后续命令的发送。");
    }
}
